import { createRouter, createWebHashHistory } from "vue-router";
import routes from "@/router/routes.js";
import { getToken } from "@/utils/auth";

// 创建路由实例
const router = createRouter({
	history: createWebHashHistory(), // 使用HTML5 Hash模式
	routes,
});

router.beforeEach((to, from, next) => {
	const token = getToken();
	if (to.matched.length === 0) {
		return next({ name: "Err404" });
	}
	const requiresAuth = to.matched.some((record) => record.meta.auth);
	if (requiresAuth) {
		if (token) {
			next();
		} else {
			next("/");
		}
		return;
	} else {
		return next();
	}
});

export default router;
